require "rubygems"
require "fileutils"
require "hpricot"

def copy_skel
  src = "skel" #Change to skel_sqlite to use Sqlite3 class.
  dst = "fanfou"
  if File.exists?(dst)
    FileUtils.rm_rf(dst)
  end
  FileUtils.cp_r(src, dst)
rescue
  puts "Unable to copy '#{src}' to '#{dst}'."
end

def read_vars(url)
  opts = {}
  file = File.open(File.join(File.expand_path(url), "status_1.html"))
  doc = Hpricot(file)
  doc.search("link").each do |link|
    if link.attributes["rel"] == "alternate"
      title = link.attributes["title"].split('_')
      title.pop
      opts["shortname"] = title.join('_')
    end
  end
  doc.search("style") do |s|
    opts["style"] = s.inner_html
  end
  doc.search("h1") do |h1|
    opts["name"] = h1.inner_html
  end
  doc.search("li#bio/span") do |s|
    opts["desc"] = s.inner_html
  end
  doc.search("div#iconset") do |d|
    opts["icons"] = d.inner_html
  end
  arr = []
  doc.search("ul#user_stats/li/a/span.count") do |s|
    arr << s.inner_html
  end
  opts["followings"], opts["followers"], opts["statuses"] = arr
  doc.search("div#footer//span") do |s|
    opts["uuid"] = s.attributes["title"]
  end
  opts
end

def make_config_file(url)
  dst = "fanfou"
  dst_conf = "#{dst}/config.inc.php"
  if File.exist?(dst_conf)
    FileUtils.rm_f(dst_conf)
  end
  
  opts = read_vars(url)
  
  file = File.open(dst_conf, "w")
  content = <<OVER
<?
  define("NAME", "#{opts['name']}");
  define('SHORTNAME', "#{opts['shortname']}");
  define("DESC", "#{opts['desc']}");
  //define("STATUSES", "#{opts['statuses']}") // If you want the original count, uncomment this line.
  define("FOLLOWERS", "#{opts['followers']}");
  define("FOLLOWINGS", "#{opts['followings']}");
  define('NUM_PER_PAGE', 25);
  define("PHOTOS_PER_PAGE", 20);
  define('UUID', '"#{opts['uuid']}"');

  $icons = <<<END
#{opts['icons']}
END;
  $style = <<<END
#{opts['style']}
END;
OVER
  file.puts content
  file.close
end

copy_skel
make_config_file(ARGV[0])
